package flexconsole.view.renderers {
	import flash.events.Event;
	
	import flexconsole.controls.SchrodingerCheckBox;
	import flexconsole.events.CategoryEvent;
	
	import mx.controls.treeClasses.TreeItemRenderer;
	
	/**
	 * Special item renderer for the Category tree that implements the display logic of the Category selection state.
	 * @author ivanchoo
	 *
	 */
	public class CategoryTreeCheckboxItemRenderer extends TreeItemRenderer {
		protected var checkbox:SchrodingerCheckBox;
		
		public function CategoryTreeCheckboxItemRenderer() {
			super();
		}
		
		override protected function commitProperties():void {
			super.commitProperties();
			updateControls();
		}
		
		override protected function createChildren():void {
			super.createChildren();
			checkbox = new SchrodingerCheckBox();
			addChild(checkbox);
			checkbox.addEventListener(Event.CHANGE, onCheckboxChange);
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
			super.updateDisplayList(unscaledWidth, unscaledHeight);
			const xOffset:int = 2;
			checkbox.x = label.x + xOffset;
			checkbox.y = label.y;
			checkbox.width = label.width - xOffset;
			checkbox.height = label.height;
			checkbox.label = checkbox.toolTip = label.text;
			label.visible = false;
			checkbox.visible = true;
			updateControls();
		}
		
		protected function onCheckboxChange(event:Event):void {
			//   bubble up the change event
			dispatchEvent(new CategoryEvent(CategoryEvent.SELECTION_CHANGE, data as XML, checkbox.selected));
		}
		
		protected function updateControls():void {
			var xml:XML = data as XML;
			
			var selected:Boolean = false;
			var schrodinger:Boolean = false;
			
			if (xml) {
				selected = xml.hasOwnProperty("@selected") ? xml.@selected == "true" : false;
				
				if (xml.children().length() > 0) {
					var numSelected:int = xml.descendants("*").(attribute("selected") == "true").length();
					var numNotSelected:int = xml.descendants("*").(attribute("selected") == "false").length();
					schrodinger = selected ? numNotSelected > 0 : numSelected > 0;
				}
			}
			checkbox.data = data;
			checkbox.selected = selected;
			checkbox.schrodinger = schrodinger;
			checkbox.setStyle("color", getStyle(selected ? "color" : "disabledColor"));
		}
	}
}